package com.zzyl.nursing.service.impl;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.nursing.service.WechatService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class WechatServiceImpl implements WechatService {
    // 登录
    private static final String REQUEST_URL = "https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code";

    // 获取token
    private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";

    // 获取手机号
    private static final String PHONE_REQUEST_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";

    @Value("${wechat.AppID}")
    private String appId;

    @Value("${wechat.AppSecret}")
    private String appSecret;

    /**
     * 获取openId
     *
     * @param code 小程序传递的code值
     * @return openId
     */
    @Override
    public String getOpenId(String code) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("appid", appId);
        paramMap.put("secret", appSecret);
        paramMap.put("js_code", code);

        String result = HttpUtil.get(REQUEST_URL, paramMap);

        // 将结果转成JSON对象
        JSONObject jsonObject = JSONObject.parseObject(result);

        // 判断返回结果中的异常情况，如果errcode不为空，证明出错了
        if (ObjectUtils.isNotEmpty(jsonObject.getInteger("errcode"))) {
            // 如果错误码不为空，证明出错了
            throw new BaseException(jsonObject.getString("errmsg"));
        }

        return jsonObject.getString("openid");
    }

    /**
     * 获取小程序用户的手机号
     *
     * @param detailCode 小程序传递的detailCode值
     * @return 手机号
     */
    @Override
    public String getPhoneNumber(String detailCode) {
        // 调用方法获取accessToken
        String accessToken = getAccessToken();

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("code", detailCode);

        // 调用微信接口获取手机号
        String result = HttpUtil.post(PHONE_REQUEST_URL + accessToken, JSON.toJSONString(paramMap));

        JSONObject jsonObject = JSONObject.parseObject(result);

        // 判断异常情况
        if (!jsonObject.getInteger("errcode").equals(0)) {
            throw new BaseException(jsonObject.getString("errmsg"));
        }

        // 返回手机号
        return jsonObject.getJSONObject("phone_info").getString("phoneNumber");
    }

    /**
     * 获取accessToken
     * @return accessToken
     */
    private String getAccessToken() {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("appid", appId);
        paramMap.put("secret", appSecret);
        String result = HttpUtil.get(TOKEN_URL, paramMap);

        // 将结果解析为JSON对象
        JSONObject jsonObject = JSONObject.parseObject(result);

        if (ObjectUtils.isNotEmpty(jsonObject.getInteger("errcode"))) {
            // 如果错误码不为空，证明出错了
            throw new BaseException(jsonObject.getString("errmsg"));
        }

        return jsonObject.getString("access_token");
    }
}
